package com.taikang.hmp.frame.login.action.view;

import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taikang.hmp.frame.common.ErrorConstant;
import com.taikang.hmp.frame.common.TKException;
import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.datastructre.support.ResponseDto;
import com.taikang.hmp.frame.common.properties.PropertiesHelper;
import com.taikang.hmp.frame.common.tools.MD5Util;
import com.taikang.hmp.frame.common.web.action.BaseAction;
import com.taikang.hmp.frame.common.web.remotecall.security.uidlimit.AppUidStatusFactory;
import com.taikang.hmp.frame.common.web.session.AppSessionFactory;
import com.taikang.hmp.frame.common.web.session.SessionBean;
import com.taikang.hmp.frame.login.service.ILoginService;
import com.taikang.hmp.frame.user.bean.AuthUserInfo;

public class LoginAction  extends  BaseAction{
	protected final Log log = LogFactory.getLog(getClass());

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;


	private static Logger logger = LoggerFactory.getLogger(LoginAction.class);

	
	private ILoginService      loginService;
	

	

	public ILoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(ILoginService loginService) {
		this.loginService = loginService;
	}

	

	public String executeAction() {
		 if("login".equals(requestDto.getMethod())){
			return login();
		}
		 else if("taipinglogin".equals(requestDto.getMethod())){
				return taipinglogin();
			}else{
			throw new TKException("no support method:"+requestDto.getMethod());
		}
	}
	
	/**
	 * 太平登录
	 */
	public String taipinglogin(){
		//通用校验
		ResponseDto responseDto = new ResponseDto();
			
		//获取参数
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		
		//
		String code = paramDto.getAsString("code");
		String url = PropertiesHelper.appHelper.getValue("ThreeUrl")+"/api/oauth/token?grant_type=authorization_code&third_id=HEALTH_HD&code="+code;
		String result =  httpGet(url);
		JSONObject obj = JSONObject.fromObject(result);
		if(obj.getString("access_token")!=null && obj.getString("access_token").length()>0){
			
		String url2 = PropertiesHelper.appHelper.getValue("ThreeUrl")+"/api/oauth/user?third_id=HEALTH_HD&access_token="+obj.getString("access_token");
		String result2 =  httpGet(url2);
		JSONObject obj2 = JSONObject.fromObject(result2);
		List<AuthUserInfo> info = loginService.getInfo(obj2.getString("user_code"));
		if(info.size()>0){
			String userid = info.get(0).getUser_id();
			String requestsource = requestDto.getRequestsource();
			
				//保存session
				SessionBean sessionInfo = loginService.getCustomerBasicInfo(userid);
				String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
				//保存用户状态
				AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(userid,requestsource);
				//
				responseDto.setSessionid(sessionId);
				responseDto.setUid(userid);
			
		}else{
			String userid = loginService.saveTaipingRegistInfo(paramDto,obj2.getString("user_code"));
			String requestsource = requestDto.getRequestsource();
			
			//保存session
			SessionBean sessionInfo = loginService.getCustomerBasicInfo(userid);
			String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
			//保存用户状态
			AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(userid,requestsource);
			//
			responseDto.setSessionid(sessionId);
			responseDto.setUid(userid);
		}

		}else{
			responseDto.addErrorCode(ErrorConstant.HD_NO_TOKEN);
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
	/**
	 * 登录
	 */
	public String login(){
		//通用校验
		ResponseDto responseDto = new ResponseDto();
			
		//获取参数
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		String requestsource = requestDto.getRequestsource();
		//
		String usn = paramDto.getAsString("username");
		String pwd =MD5Util.stringMD5(paramDto.getAsString("password"));
		List<AuthUserInfo> info = loginService.getLoginInfo(usn);
		if(info.size()>0){
			String userid = info.get(0).getUser_id();
			//密码一致
			if(pwd.equals(info.get(0).getUser_pwd())){
				//保存session
				SessionBean sessionInfo = loginService.getCustomerBasicInfo(userid);
				String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
				//保存用户状态
				AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(userid,requestsource);
				//
				responseDto.setSessionid(sessionId);
				responseDto.setUid(userid);
			}
			//密码不一致
			else{
				//保存用户状态
				AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginFail(userid,requestsource);
				//
				responseDto.addErrorCode(ErrorConstant.HD_PASSWORD_ERR);
			}
		}else{
			responseDto.addErrorCode(ErrorConstant.HD_USER_NOT_EXIST);
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
	// 辅助函数: 使用 GET 方式发起一个 HTTP 请求, 并返回结果
    private static String httpGet(String url)
    {
    
         
        String response=new String();
        CloseableHttpClient client = HttpClients.createDefault();
       
        //使用POST方法
        HttpGet method = new HttpGet(url);  
       
        
        
        try{
       	 CloseableHttpResponse httpResponse =   client.execute(method);
       	 HttpEntity entity = httpResponse.getEntity();
            if (null != entity){
           	 
                if(httpResponse.getStatusLine().getStatusCode()==200)
                {
                    response = EntityUtils.toString(entity);
                }
            }
        }catch (Exception ex)
        {
           ex.printStackTrace();
        }

        
       
        //释放连接
        method.releaseConnection();
        // 转换编码
        //return Utility.utf8Togb2312(response);
        return response;
    }

}
